package com.dhy.replugin

import com.facebook.drawee.view.SimpleDraweeView
import com.qihoo360.replugin.RePluginClassLoader

/**
 *  FRESCO_VERSION = '1.13.0'
 * */
class FrescoShareClass : IShareLibClass {
    private val notSharedClass: Array<String> = arrayOf(
        "com.facebook.drawee.generic.GenericDraweeHierarchyInflater",
        "com.facebook.drawee.view.GenericDraweeView",
        "com.facebook.drawee.view.SimpleDraweeView"
    )

    init {
        if (BuildConfig.DEBUG) {
            val loader = javaClass.classLoader!!
            notSharedClass.forEach {
                loader.loadClass(it)
            }
        }
    }

    override fun loadClass(hostClassLoader: RePluginClassLoader, superLoadClass: (String) -> Class<*>, name: String): Class<*>? {
        return if (name.startsWith("com.facebook.")) {
            if (notSharedClass.contains(name) || name.startsWith("com.facebook.drawee.R$")) {
                if (name == "com.facebook.drawee.view.SimpleDraweeView") {
                    val cls = superLoadClass(name)
                    fixShareFresco(cls)
                    cls
                } else superLoadClass(name)
            } else hostClassLoader.loadClass(name)
        } else null
    }

    private fun fixShareFresco(pluginSimpleDraweeViewClass: Class<*>) {
        try {
            val hostField = SimpleDraweeView::class.java.getDeclaredField("sDraweecontrollerbuildersupplier")
            hostField.isAccessible = true
            val hostSupplier = hostField.get(null)//host

            val pluginFiled = pluginSimpleDraweeViewClass.getDeclaredField("sDraweecontrollerbuildersupplier")
            pluginFiled.isAccessible = true
            pluginFiled.set(null, hostSupplier)
        } catch (e: Exception) {
            throw IllegalStateException("fixShareSimpleDraweeView failed", e)
        }
    }
}